package com.yunyao.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyao.common.constant.ConstantsUtils;
import com.yunyao.common.constant.enums.ContractPriceType;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.constant.enums.DateFormatPattern;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.core.UserInfoRequest;
import com.yunyao.common.dto.*;
import com.yunyao.common.dto.excel.InvoiceExcelDto;
import com.yunyao.common.dto.project.ProjectDto;
import com.yunyao.common.dto.supplier.SupplierSettlementDto;
import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.StringUtils;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.mapper.BamuPaymentContractInvoiceMapper;
import com.yunyao.dao.mapper.BamuPurchaseContractMapper;
import com.yunyao.dao.mapper.BamuReconciliationSettlementMapper;
import com.yunyao.dao.mapper.BamuSaleContractMapper;
import com.yunyao.dao.model.*;
import com.yunyao.dao.service.bamu.*;
import com.yunyao.framework.dto.invoice.InvoiceConfirmDto;
import com.yunyao.framework.service.SoInvoiceService;
import com.yunyao.framework.vo.Invoice.*;
import com.yunyao.framework.vo.reconciliation.ReconciliationOrderVO;
import com.yunyao.framework.vo.supplier.SupplierSettlementVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SoInvoiceServiceImpl implements SoInvoiceService {
    @Autowired
    private IBamuSaleContractService iBamuSaleContractService;
    @Autowired
    private IBamuContractWirePayService iBamuContractWirePayService;
    @Autowired
    private IBamuSpReconciliationSettlementService iBamuSpReconciliationSettlementService;
    @Autowired
    private IBamuInvoiceApplyService iBamuInvoiceApplyService;
    @Autowired
    private IBamuAuditConfirmHistoryService iBamuAuditConfirmHistoryService;
    @Autowired
    private IBamuInvoiceSourceOrderService iBamuInvoiceSourceOrderService;
    @Autowired
    private IBamuInvoiceSourceService iBamuInvoiceSourceService;
    @Autowired
    private IBamuInvoiceService iBamuInvoiceService;
    @Autowired
    private IBamuReconciliationSettlementService iBamuReconciliationSettlementService;
    @Autowired
    private IBamuReconciliationService iBamuReconciliationService;
    @Autowired
    private IBamuPurchaseApplyService iBamuPurchaseApplyService;
    @Autowired
    private IBamuReconciliationOrderService iBamuReconciliationOrderService;

    @Resource
    private BamuPaymentContractInvoiceMapper bamuPaymentContractInvoiceMapper;

    @Resource
    private BamuPurchaseContractMapper bamuPurchaseContractMapper;


    @Override
    public YResult<PageResult<InvoiceVO>> pageList(InvoiceDto invoiceDto) {
        //构建查询条件
        LambdaQueryWrapper<BamuInvoice> queryWrapper = new LambdaQueryWrapper<BamuInvoice>().
//                eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuReconciliation::getContractId,invoiceDto.getContractId()).
        like(StringUtils.isNotBlank(invoiceDto.getContractNo()), BamuInvoice::getContractNo, invoiceDto.getContractNo())
                .like(StringUtils.isNotBlank(invoiceDto.getContractName()), BamuInvoice::getContractName, invoiceDto.getContractName())
                .eq(StringUtils.isNotBlank(invoiceDto.getProjectId()), BamuInvoice::getProjectId, invoiceDto.getProjectId())
                .like(StringUtils.isNotBlank(invoiceDto.getProjectName()), BamuInvoice::getProjectName, invoiceDto.getProjectName())
                .eq(StringUtils.isNotBlank(invoiceDto.getPurchaseDeptId()), BamuInvoice::getPurchaseDeptId, invoiceDto.getPurchaseDeptId())
                .like(StringUtils.isNotBlank(invoiceDto.getPurchaseDeptName()), BamuInvoice::getPurchaseDeptName, invoiceDto.getPurchaseDeptName())
//                .eq(StringUtils.isNotBlank((CharSequence) invoiceDto.getInvoicingDate()),BamuInvoice::getInvoicingDate,invoiceDto.getInvoicingDate())
                .between(StringUtils.isNotBlank(invoiceDto.getBeginDate()) && StringUtils.isNotBlank(invoiceDto.getEndDate()), BamuInvoice::getInvoicingDate,
                        ConvertUtil.getStartOfDay(ConvertUtil.getString2Date(invoiceDto.getBeginDate())), ConvertUtil.getEndOfDay(ConvertUtil.getString2Date(invoiceDto.getEndDate())))
                .eq(StringUtils.isNotBlank((CharSequence) invoiceDto.getInvoicingPrice()), BamuInvoice::getInvoicingPrice, invoiceDto.getInvoicingPrice())
//                .eq(StringUtils.isNotBlank(invoiceDto.getInvoicingStatus()),BamuInvoice::getInvoicingStatus,invoiceDto.getInvoicingStatus())
                .eq(StringUtils.isNotBlank(invoiceDto.getInvoiceBindStatus()), BamuInvoice::getInvoiceBindStatus, invoiceDto.getInvoiceBindStatus())
                .in(!Objects.isNull(invoiceDto.getStatusList()), BamuInvoice::getStatus, invoiceDto.getStatusList())
//                .eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuInvoice::getStatus,invoiceDto.getStatusList())
                .eq(StringUtils.isNotBlank(invoiceDto.getContractMethod()), BamuInvoice::getContractMethod, invoiceDto.getContractMethod())
                .eq(BamuInvoice::getInvoiceDataType, 0)
                .eq(BamuInvoice::getIsDeleted, 0)
                .orderByDesc(BamuInvoice::getCreatedAt)
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuInvoice::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()), BamuInvoice::getSupplierDeptId, BaseContext.getSupplierList());
//                .eq(StringUtils.isNotBlank(invoiceDto.getInvoiceDataType()),BamuInvoice::getInvoiceDataType,invoiceDto.getInvoiceDataType());
//                .eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuInvoice::getStatus,invoiceDto.getStatus());
        // 分页查询
        IPage<BamuInvoice> invoicePage = new Page<>(invoiceDto.getPageIndex(), invoiceDto.getPageSize());
        invoicePage = iBamuInvoiceService.page(invoicePage, queryWrapper);
        // 处理查询结果
        if (CollectionUtils.isEmpty(invoicePage.getRecords())) {
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<InvoiceVO> invoiceVOList = daoToVoList6(invoicePage.getRecords());
        //处理预期剩余时间
        getRangeDays(invoiceVOList);
        // 返回分页结果
        return YResult.success(new PageResult<>(invoiceVOList, invoicePage.getCurrent(), invoicePage.getSize(), invoicePage.getPages(), invoicePage.getTotal()));
    }


    @Override
    public PageResult<InvoiceVO> findByTypeList(@Valid @NotNull InvoiceTypeDto dto) {
        if (dto.getInvoiceDataType().equals("1")) {
            List<String> pcIds = bamuPurchaseContractMapper.findByContractId(dto.getContractId());
            dto.setIds(pcIds);
        } else {
            List<String> scIds = iBamuSaleContractService.findByContractId(dto.getContractId());
            dto.setIds(scIds);
        }
        List<BamuInvoice> invoices = bamuPaymentContractInvoiceMapper.findByTypeList(dto);
        // 处理查询结果
        if (CollectionUtils.isEmpty(invoices)) {
            return new PageResult<>();
        }
        // 转换为VO对象列表
        List<InvoiceVO> invoiceVOList = daoToVoList6(invoices);
        // 返回分页结果
        return new PageResult<>(invoiceVOList, dto.getPageIndex(), dto.getPageSize());

    }

    /**
     * 关联发票
     *
     * @param dto
     * @return
     */
    public boolean relationInvoice(@Valid @NotNull RelationInvoiceDto dto) {
        return iBamuInvoiceService.lambdaUpdate()
                .in(BamuInvoice::getId, dto.getRelationInvoiceIds())
                .eq(BamuInvoice::getInvoiceBindStatus, ConstantsUtils.INVOICE_BIND_STATUS_0)
                .eq(BamuInvoice::getIsDeleted, DataDeletedStatus.NO.getType())
                .set(BamuInvoice::getInvoiceBindId, dto.getInvoiceBindId())
                .set(StringUtils.isNotBlank(dto.getInvoiceBindName()), BamuInvoice::getInvoiceBindName, dto.getInvoiceBindName())
                .set(BamuInvoice::getInvoiceBindStatus, ConstantsUtils.INVOICE_BIND_STATUS_1)
                .update();
    }


    /**
     * 获取逾期日期天数
     *
     * @param invoiceVOList 列表数据
     */
    private void getRangeDays(List<InvoiceVO> invoiceVOList) {
        Date nowDate = new Date();
        invoiceVOList.forEach(e -> {
            if (e.getExpectPaymentDate() != null) {
                long diff = e.getExpectPaymentDate().getTime() - nowDate.getTime();
                long day = diff / (1000 * 60 * 60 * 24);
                e.setExpectPaymentNum(day);
            }
        });
    }

    @Override
    public YResult<PageResult<SupplierSettlementVO>> pageSementList(SupplierSettlementDto supplierSettlementDto) {
        // 构建查询条件
        LambdaQueryWrapper<BamuSpReconciliationSettlement> queryWrapper = new LambdaQueryWrapper<BamuSpReconciliationSettlement>()
                .eq(BamuSpReconciliationSettlement::getIsDeleted, DataDeletedStatus.NO.getType())
                .eq(org.apache.commons.lang3.StringUtils.isNotBlank(supplierSettlementDto.getContractId()),
                        BamuSpReconciliationSettlement::getContractId,
                        supplierSettlementDto.getContractId())
//                        .like(org.apache.commons.lang3.StringUtils.isNotBlank(supplierSettlementDto.getInvoiceSource),
//                                BamuSpReconciliationSettlement::getProjectName,
//                                supplierSettlementDto.getProjectName())
//                        .like(org.apache.commons.lang3.StringUtils.isNotBlank(supplierSettlementDto.getSupplierDeptName()),
//                                BamuSpReconciliationSettlement::getSupplierDeptName,
//                                supplierSettlementDto.getSupplierDeptName())
                .orderByDesc(BamuSpReconciliationSettlement::getId);

        // 分页查询
        IPage<BamuSpReconciliationSettlement> settlementPage =
                new Page<>(supplierSettlementDto.getPageIndex(),
                        supplierSettlementDto.getPageSize());
        settlementPage = iBamuSpReconciliationSettlementService.page(settlementPage, queryWrapper);

        // 处理查询结果
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(settlementPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<SupplierSettlementVO> voList = daoToVoList0(settlementPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(voList, settlementPage.getCurrent(),
                settlementPage.getSize(), settlementPage.getPages(), settlementPage.getTotal()));
    }

    private List<SupplierSettlementVO> daoToVoList0(List<BamuSpReconciliationSettlement> records) {
        List<String> contractIdList =
                records.stream().map(BamuSpReconciliationSettlement::getContractId).distinct().toList();
        Map<String, BamuContractWirePay> contractWirePayMap = new HashMap<>();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(contractIdList)) {
            contractWirePayMap.putAll(iBamuContractWirePayService.mapByContractIdList(contractIdList));
        }
        return records.stream().map(x -> daoToVo0(x, contractWirePayMap)).collect(Collectors.toList());
    }

    /**
     * 将数据访问对象（DAO）层的数据转换为视图对象（VO）
     * 该方法主要用于供应商结算数据的转换，以便在不同层面上使用
     *
     * @param bamuSpReconciliationSettlement 供应商结算数据对象，包含详细的结算信息
     * @param contractWirePayMap             合约与支付方式的映射，用于补充结算数据中的合约支付方式信息
     * @return 返回转换后的 SupplierSettlementVO 对象，该对象包含了转换后的供应商结算信息
     */
    private SupplierSettlementVO daoToVo0(BamuSpReconciliationSettlement bamuSpReconciliationSettlement, Map<String, BamuContractWirePay> contractWirePayMap) {
        // 初始化供应商结算视图对象
        SupplierSettlementVO vo = new SupplierSettlementVO();
        // 将结算数据对象的基本属性复制到视图对象中
        BeanUtils.copyProperties(bamuSpReconciliationSettlement, vo);
        // 从合约支付方式映射中获取与当前结算数据相关的合约支付方式
        BamuContractWirePay contractWirePay = contractWirePayMap.get(bamuSpReconciliationSettlement.getContractId());
        // 如果合约支付方式存在，则将其类型设置到视图对象中
        if (Objects.nonNull(contractWirePay)) {
            vo.setPriceType(contractWirePay.getPriceType());
            vo.setPriceTypeDesc(ContractPriceType.typeOfDesc(Integer.valueOf(contractWirePay.getPriceType())));
            vo.setPaymentCycle(contractWirePay.getPaymentCycle());
        }
        // 返回转换后的视图对象
        return vo;
    }

    private List<BamuInvoiceSource> getBamuInvoiceSource(String id) {
        LambdaQueryWrapper<BamuInvoiceSource> wrapper = new LambdaQueryWrapper<BamuInvoiceSource>()
                .eq(BamuInvoiceSource::getInvoiceId, id);
        List<BamuInvoiceSource> bamuInvoiceSourceList = iBamuInvoiceSourceService.list(wrapper);
        return bamuInvoiceSourceList;
    }

    private List<InvoiceVO> daoToVoList6(List<BamuInvoice> records) {
        return records.stream().map(this::daoToVo6).collect(Collectors.toList());
    }

    private InvoiceVO daoToVo6(BamuInvoice bamuInvoice) {
        InvoiceVO invoiceVO = new InvoiceVO();
        BeanUtils.copyProperties(bamuInvoice, invoiceVO);
//        List<BamuInvoiceSource> source = getBamuInvoiceSource(bamuInvoice.getId());
//        if (source.size() != 0) {
//            for (BamuInvoiceSource source1 : source) {
//                invoiceVO.setOrderNum(source1.getOrderNum());
//                invoiceVO.setOrderInvoiceNum(source1.getOrderInvoiceNum());
//                int ordercanInvoiceNum = source1.getOrderNum() - source1.getOrderInvoiceNum();
//                invoiceVO.setOrdercanInvoiceNum(ordercanInvoiceNum);
//            }
//        }else {
//            invoiceVO.setOrderNum(0);
//            invoiceVO.setOrderInvoiceNum(0);
//            invoiceVO.setOrdercanInvoiceNum(0);
//        }
        return invoiceVO;
    }

    private List<InvoiceVO> daoToVoList(List<BamuInvoice> records) {
        return records.stream().map(this::daoToVo).collect(Collectors.toList());
    }

    private InvoiceVO daoToVo(BamuInvoice bamuInvoice) {
        InvoiceVO invoiceVO = new InvoiceVO();
        BeanUtils.copyProperties(bamuInvoice, invoiceVO);
        return invoiceVO;
    }


    @Override
    public YResult<InvoiceinfoVO> getInvoiceById(Long id) {
        LambdaQueryWrapper<BamuInvoice> wrapper = new LambdaQueryWrapper<BamuInvoice>()
                .eq(BamuInvoice::getId, id);
        BamuInvoice bamuInvoice = iBamuInvoiceService.getOne(wrapper);
        // 处理查询结果
        if (Objects.isNull(bamuInvoice)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        return YResult.success(daoToInfoVO(bamuInvoice));
    }

    private InvoiceinfoVO daoToInfoVO(BamuInvoice bamuInvoice) {
        InvoiceinfoVO invoiceinfoVO = new InvoiceinfoVO();
        BeanUtils.copyProperties(bamuInvoice, invoiceinfoVO);
        return invoiceinfoVO;
    }

    @Override
    public YResult<String> saveInfo(InvoiceDto saveDto) {
        BamuInvoice bamuInvoice = new BamuInvoice();
        BeanUtils.copyProperties(saveDto, bamuInvoice);
        BamuSaleContract bamuSaleContract = iBamuSaleContractService.getById(saveDto.getContractId());
        bamuInvoice.setInvoiceDataType("0");
        bamuInvoice.setProjectName(bamuSaleContract.getProjectName());
        bamuInvoice.setContractNo(bamuSaleContract.getContractNo());
        bamuInvoice.setInvoicingDate(ConvertUtil.getString2Date(saveDto.getInvoicingDate()));
        bamuInvoice.setInvoiceReceiveDate(ConvertUtil.getString2Date(saveDto.getInvoiceReceiveDate()));
        bamuInvoice.setInvoicingNo(saveDto.getInvoicingNo());
        bamuInvoice.setContractMethod(saveDto.getContractMethod());
        bamuInvoice.setSupplierDeptId(bamuSaleContract.getSupplierDeptId());
        bamuInvoice.setSupplierDeptName(bamuSaleContract.getSupplierDeptName());
        bamuInvoice.setProjectId(bamuSaleContract.getProjectId());
        bamuInvoice.setProjectName(bamuSaleContract.getProjectName());
        iBamuInvoiceService.saveOrUpdate(bamuInvoice);


        LambdaQueryWrapper<BamuPurchaseApply> wrapper2 = new LambdaQueryWrapper<BamuPurchaseApply>()
                .eq(BamuPurchaseApply::getContractId, bamuInvoice.getContractId());
        List<BamuPurchaseApply> bamuPurchaseApplylist = iBamuPurchaseApplyService.list(wrapper2);
        if (CollectionUtils.isNotEmpty(bamuPurchaseApplylist)) {
            for (BamuPurchaseApply b : bamuPurchaseApplylist) {
                BamuInvoiceApply bamuInvoiceApply = new BamuInvoiceApply();
                BeanUtils.copyProperties(bamuInvoice, bamuInvoiceApply);
                bamuInvoiceApply.setApplyId(b.getId());
                bamuInvoiceApply.setInvoiceId(bamuInvoice.getId());
                iBamuInvoiceApplyService.saveOrUpdate(bamuInvoiceApply);
                b.setProjectInvoiceStatus("1");
                iBamuPurchaseApplyService.saveOrUpdate(b);
            }
        }

//        bamuInvoice.setCreatedAt(saveDto.getCreatedAt());
//        bamuInvoice.setReconciliationStartDate(saveDto.getReconciliationStartDate());
//        bamuInvoice.setReconciliationEndDate(saveDto.getReconciliationEndDate());
        if (CollectionUtils.isNotEmpty(saveDto.getReconciliationList())) {
            LambdaQueryWrapper<BamuReconciliationSettlement> projectWrapper = new LambdaQueryWrapper<BamuReconciliationSettlement>()
                    .in(BamuReconciliationSettlement::getId, saveDto.getReconciliationList());
            List<BamuReconciliationSettlement> bamuReconciliationSettlement = iBamuReconciliationSettlementService.list(projectWrapper);
            if (CollectionUtils.isNotEmpty(bamuReconciliationSettlement)) {
                for (int i = 0; i < bamuReconciliationSettlement.size(); i++) {
                    BamuReconciliationSettlement settlement = bamuReconciliationSettlement.get(i);
                    BamuInvoiceSource bamuInvoiceSource = new BamuInvoiceSource();
                    BeanUtils.copyProperties(bamuReconciliationSettlement.get(i), bamuInvoiceSource);
                    bamuInvoiceSource.setInvoiceId(bamuInvoice.getId());
                    bamuInvoiceSource.setBizId(bamuReconciliationSettlement.get(i).getId());
                    bamuInvoiceSource.setReconciliationCycle(ConvertUtil.getFormatDate(settlement.getReconciliationStartDate(), false, DateFormatPattern.YEAR_MONTH_DAY.getPattern())
                            + "至" + ConvertUtil.getFormatDate(settlement.getReconciliationEndDate(), false, DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
                    bamuInvoiceSource.setSettlementTotalPrice(settlement.getReconciliationPrice());
                    iBamuInvoiceSourceService.saveOrUpdate(bamuInvoiceSource);
                }
            }
        } else if (CollectionUtils.isNotEmpty(saveDto.getPurchaseapplyIdList())) {
            LambdaQueryWrapper<BamuPurchaseApply> projectWrapper1 = new LambdaQueryWrapper<BamuPurchaseApply>()
                    .in(BamuPurchaseApply::getId, saveDto.getPurchaseapplyIdList())
                    .eq(BamuPurchaseApply::getIsDeleted, 0);
            List<BamuPurchaseApply> bamuPurchaseApply = iBamuPurchaseApplyService.list(projectWrapper1);
            if (CollectionUtils.isNotEmpty(bamuPurchaseApply)) {
                for (int i = 0; i < bamuPurchaseApply.size(); i++) {
                    LambdaQueryWrapper<BamuReconciliationSettlement> projectWrapper = new LambdaQueryWrapper<BamuReconciliationSettlement>()
                            .eq(BamuReconciliationSettlement::getContractName, saveDto.getContractName());
                    List<BamuReconciliationSettlement> bamuReconciliationSettlement = iBamuReconciliationSettlementService.list(projectWrapper);
                    if (CollectionUtils.isNotEmpty(bamuReconciliationSettlement)) {
                        for (int j = 0; j < bamuReconciliationSettlement.size(); j++) {
                            BamuReconciliationSettlement settlement = bamuReconciliationSettlement.get(j);
                            BamuInvoiceSource bamuInvoiceSource = new BamuInvoiceSource();
                            BeanUtils.copyProperties(bamuReconciliationSettlement.get(j), bamuInvoiceSource);
                            bamuInvoiceSource.setInvoiceId(bamuInvoice.getId());
                            bamuInvoiceSource.setBizId(bamuReconciliationSettlement.get(j).getId());
                            bamuInvoiceSource.setReconciliationCycle(ConvertUtil.getFormatDate(settlement.getReconciliationStartDate(), false, DateFormatPattern.YEAR_MONTH_DAY.getPattern())
                                    + "至" + ConvertUtil.getFormatDate(settlement.getReconciliationEndDate(), false, DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
                            bamuInvoiceSource.setSettlementTotalPrice(settlement.getReconciliationPrice());
                            iBamuInvoiceSourceService.saveOrUpdate(bamuInvoiceSource);
                        }
                    }
                }
            }
        }
        iBamuInvoiceService.saveOrUpdate(bamuInvoice);

        return YResult.success(bamuInvoice.getId());
    }

    @Override
    public YResult<String> saveInvoice(InvoiceDto saveDto) {
        LambdaQueryWrapper<BamuInvoice> wrapper = new LambdaQueryWrapper<BamuInvoice>()
                .eq(BamuInvoice::getId, saveDto.getId());
        BamuInvoice bamuInvoice = iBamuInvoiceService.getOne(wrapper);
        BamuInvoice bamuInvoice1 = new BamuInvoice();
        BeanUtils.copyProperties(bamuInvoice, bamuInvoice1);
        bamuInvoice1.setStatus(6);
        iBamuInvoiceService.saveOrUpdate(bamuInvoice1);
        return YResult.success(bamuInvoice1.getId());
    }

    @Override
    public YResult<PageResult<InvoiceVO>> pageInvoiceList(InvoiceDto invoiceDto) {
        //构建查询条件
        LambdaQueryWrapper<BamuInvoice> queryWrapper = new LambdaQueryWrapper<BamuInvoice>().
                eq(StringUtils.isNotBlank(invoiceDto.getContractId()), BamuInvoice::getContractId, invoiceDto.getContractId())
//                .eq(StringUtils.isNotBlank(invoiceDto.getInvoiceDataType()),BamuInvoice::getInvoiceDataType,invoiceDto.getInvoiceDataType())
                .eq(StringUtils.isNotBlank(invoiceDto.getInvoiceBindStatus()), BamuInvoice::getInvoiceBindStatus, invoiceDto.getInvoiceBindStatus())
                .eq(StringUtils.isNotBlank(invoiceDto.getInvoicingStatus()), BamuInvoice::getInvoicingStatus, invoiceDto.getInvoicingStatus())
                .between(StringUtils.isNotBlank(invoiceDto.getBeginDate()) && StringUtils.isNotBlank(invoiceDto.getEndDate()), BamuInvoice::getInvoicingDate,
                        ConvertUtil.getStartOfDay(ConvertUtil.getString2Date(invoiceDto.getBeginDate())), ConvertUtil.getEndOfDay(ConvertUtil.getString2Date(invoiceDto.getEndDate())))
                .eq(BamuInvoice::getInvoiceDataType, 0)
                .eq(BamuInvoice::getIsDeleted, 0);

//                .eq(StringUtils.isNotBlank(invoiceDto.getInvoiceDataType()),BamuInvoice::getInvoiceDataType,invoiceDto.getInvoiceDataType());
//                .eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuInvoice::getStatus,invoiceDto.getStatus());
        // 分页查询
        IPage<BamuInvoice> invoicePage = new Page<>(invoiceDto.getPageIndex(), invoiceDto.getPageSize());
        invoicePage = iBamuInvoiceService.page(invoicePage, queryWrapper);
        // 处理查询结果
        if (CollectionUtils.isEmpty(invoicePage.getRecords())) {
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<InvoiceVO> invoiceVOList = daoToVoList(invoicePage.getRecords());
        // 返回分页结果
        return YResult.success(new PageResult<>(invoiceVOList, invoicePage.getCurrent(), invoicePage.getSize(), invoicePage.getPages(), invoicePage.getTotal()));
    }

    @Override
    public YResult<PageResult<ReconciliationOrderVO>> pageProjectList(InvoiceDto invoiceDto) {
        List<ReconciliationOrderVO> allOrders = new ArrayList<>();
        LambdaQueryWrapper<BamuReconciliationSettlement> invoice = new LambdaQueryWrapper<BamuReconciliationSettlement>()
                .in(BamuReconciliationSettlement::getId, invoiceDto.getBizidList());
        List<BamuReconciliationSettlement> bamuReconciliationSettlementList = iBamuReconciliationSettlementService.list(invoice);
        for (BamuReconciliationSettlement settlement : bamuReconciliationSettlementList) {
            LambdaQueryWrapper<BamuReconciliation> projectWrapper = new LambdaQueryWrapper<>();
            projectWrapper.eq(BamuReconciliation::getContractId, settlement.getContractId());
            List<BamuReconciliation> bamuReconcilationList = iBamuReconciliationService.list(projectWrapper);

            for (BamuReconciliation reconciliation : bamuReconcilationList) {
                LambdaQueryWrapper<BamuReconciliationOrder> orderWrapper = new LambdaQueryWrapper<>();
                orderWrapper.eq(BamuReconciliationOrder::getReconciliationId, reconciliation.getId());

                IPage<BamuReconciliationOrder> settlementPage = new Page<>(invoiceDto.getPageIndex(), invoiceDto.getPageSize());
                settlementPage = iBamuReconciliationOrderService.page(settlementPage, orderWrapper);

                List<ReconciliationOrderVO> voList = daoToVoList1(settlementPage.getRecords(), reconciliation);
                allOrders.addAll(voList);

                // 不再在这里返回结果，而是继续处理其他数据
            }
        }

        // 检查是否查询到了数据
        if (CollectionUtils.isEmpty(allOrders)) {
            return YResult.success(new PageResult<>());
        }
        return YResult.success(new PageResult<>(allOrders, invoiceDto.getPageIndex(), invoiceDto.getPageSize(),
                (int) Math.ceil((double) allOrders.size() / invoiceDto.getPageSize()), allOrders.size()));

    }

    @Override
    public YResult<PageResult<ReconciliationOrderVO>> pageProjectList2(InvoiceDto invoiceDto) {
        List<ReconciliationOrderVO> allOrders = new ArrayList<>();
        LambdaQueryWrapper<BamuPurchaseApply> invoice = new LambdaQueryWrapper<BamuPurchaseApply>()
                .in(BamuPurchaseApply::getId, invoiceDto.getBizidList());
        List<BamuPurchaseApply> bamuReconciliationSettlementList = iBamuPurchaseApplyService.list(invoice);
        for (BamuPurchaseApply settlement : bamuReconciliationSettlementList) {
            LambdaQueryWrapper<BamuReconciliation> projectWrapper = new LambdaQueryWrapper<>();
            projectWrapper.eq(BamuReconciliation::getContractId, settlement.getContractId());
            List<BamuReconciliation> bamuReconcilationList = iBamuReconciliationService.list(projectWrapper);

            for (BamuReconciliation reconciliation : bamuReconcilationList) {
                LambdaQueryWrapper<BamuReconciliationOrder> orderWrapper = new LambdaQueryWrapper<>();
                orderWrapper.eq(BamuReconciliationOrder::getReconciliationId, reconciliation.getId());

                IPage<BamuReconciliationOrder> settlementPage = new Page<>(invoiceDto.getPageIndex(), invoiceDto.getPageSize());
                settlementPage = iBamuReconciliationOrderService.page(settlementPage, orderWrapper);

                List<ReconciliationOrderVO> voList = daoToVoList8(settlementPage.getRecords(), reconciliation);
                allOrders.addAll(voList);

                // 不再在这里返回结果，而是继续处理其他数据
            }
        }

        // 检查是否查询到了数据
        if (CollectionUtils.isEmpty(allOrders)) {
            return YResult.success(new PageResult<>());
        }
        return YResult.success(new PageResult<>(allOrders, invoiceDto.getPageIndex(), invoiceDto.getPageSize(),
                (int) Math.ceil((double) allOrders.size() / invoiceDto.getPageSize()), allOrders.size()));

    }

    private List<ReconciliationOrderVO> daoToVoList8(List<BamuReconciliationOrder> bamuReconciliationOrderList, BamuReconciliation reconciliation) {
        return bamuReconciliationOrderList.stream()
                .map(order -> {
                    ReconciliationOrderVO vo = new ReconciliationOrderVO();
                    BeanUtils.copyProperties(order, vo);
                    enrichReconciliationOrderVO(vo, reconciliation); // 使用辅助方法设置额外字段
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public YResult<PageResult<ReconciliationOrderVO>> pageProjectList3(InvoiceDto invoiceDto) {
        LambdaQueryWrapper<BamuInvoiceApply> invoiceWrapper = new LambdaQueryWrapper<BamuInvoiceApply>()
                .eq(BamuInvoiceApply::getInvoiceId, invoiceDto.getId());
        List<BamuInvoiceApply> bamuInvoiceApplyList = iBamuInvoiceApplyService.list(invoiceWrapper);
        if (CollectionUtils.isNotEmpty(bamuInvoiceApplyList)) {
            for (int i = 0; i < bamuInvoiceApplyList.size(); i++) {
                List<ReconciliationOrderVO> allOrders = new ArrayList<>();
                LambdaQueryWrapper<BamuPurchaseApply> invoice = new LambdaQueryWrapper<BamuPurchaseApply>()
                        .in(BamuPurchaseApply::getId, bamuInvoiceApplyList.get(i).getApplyId());
                List<BamuPurchaseApply> bamuReconciliationSettlementList = iBamuPurchaseApplyService.list(invoice);
                if (CollectionUtils.isNotEmpty(bamuReconciliationSettlementList)) {
                    for (BamuPurchaseApply settlement : bamuReconciliationSettlementList) {
                        LambdaQueryWrapper<BamuReconciliation> projectWrapper = new LambdaQueryWrapper<>();
                        projectWrapper.eq(BamuReconciliation::getContractId, settlement.getContractId());
                        List<BamuReconciliation> bamuReconcilationList = iBamuReconciliationService.list(projectWrapper);
                        if (CollectionUtils.isNotEmpty(bamuReconcilationList)) {
                            for (BamuReconciliation reconciliation : bamuReconcilationList) {
                                LambdaQueryWrapper<BamuReconciliationOrder> orderWrapper = new LambdaQueryWrapper<>();
                                orderWrapper.eq(BamuReconciliationOrder::getReconciliationId, reconciliation.getId());

                                IPage<BamuReconciliationOrder> settlementPage = new Page<>(invoiceDto.getPageIndex(), invoiceDto.getPageSize());
                                settlementPage = iBamuReconciliationOrderService.page(settlementPage, orderWrapper);

                                List<ReconciliationOrderVO> voList = daoToVoList8(settlementPage.getRecords(), reconciliation);
                                allOrders.addAll(voList);

                                // 不再在这里返回结果，而是继续处理其他数据
                            }
                        }
                    }
                }

                // 检查是否查询到了数据
                if (CollectionUtils.isEmpty(allOrders)) {
                    return YResult.success(new PageResult<>());
                }

                return YResult.success(new PageResult<>(allOrders, invoiceDto.getPageIndex(), invoiceDto.getPageSize(),
                        (int) Math.ceil((double) allOrders.size() / invoiceDto.getPageSize()), allOrders.size()));
            }
        }
        return YResult.success();
    }

    @Override
    public YResult<InvoiceCountVO> getcount(Long id) {
        LambdaQueryWrapper<BamuInvoiceApply> invoiceWrapper = new LambdaQueryWrapper<BamuInvoiceApply>()
                .eq(BamuInvoiceApply::getInvoiceId, id);

        List<BamuInvoiceApply> bamuInvoiceApplyList = iBamuInvoiceApplyService.list(invoiceWrapper);
        BigDecimal totalTaxPrice = BigDecimal.ZERO;
        BigDecimal reconciliationPrice = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(bamuInvoiceApplyList)) {
            for (int i = 0; i < bamuInvoiceApplyList.size(); i++) {
                List<ReconciliationOrderVO> allOrders = new ArrayList<>();
                LambdaQueryWrapper<BamuPurchaseApply> invoice = new LambdaQueryWrapper<BamuPurchaseApply>()
                        .in(BamuPurchaseApply::getId, bamuInvoiceApplyList.get(i).getApplyId());
                List<BamuPurchaseApply> bamuReconciliationSettlementList = iBamuPurchaseApplyService.list(invoice);
                if (CollectionUtils.isNotEmpty(bamuReconciliationSettlementList)) {
                    for (BamuPurchaseApply settlement : bamuReconciliationSettlementList) {
                        LambdaQueryWrapper<BamuReconciliation> projectWrapper = new LambdaQueryWrapper<>();
                        projectWrapper.eq(BamuReconciliation::getContractId, settlement.getContractId());
                        List<BamuReconciliation> bamuReconcilationList = iBamuReconciliationService.list(projectWrapper);
                        if (CollectionUtils.isNotEmpty(bamuReconcilationList)) {
                            for (BamuReconciliation reconciliation : bamuReconcilationList) {
                                LambdaQueryWrapper<BamuReconciliationOrder> orderWrapper = new LambdaQueryWrapper<>();
                                orderWrapper.eq(BamuReconciliationOrder::getReconciliationId, reconciliation.getId());
                                BamuReconciliationOrder bamuReconciliationorder = iBamuReconciliationOrderService.getOne(orderWrapper);

                                if (bamuReconciliationorder != null) {
                                    totalTaxPrice = totalTaxPrice.add(bamuReconciliationorder.getTaxTotalPrice()); // 累加税总价
                                    reconciliationPrice = reconciliationPrice.add(bamuReconciliationorder.getReconciliationPrice()); // 累加总价
                                }
                                // 不再在这里返回结果，而是继续处理其他数据
                            }

                        }
                    }
                }
            }
        }
        InvoiceCountVO invoiceCountVO = new InvoiceCountVO();
        invoiceCountVO.setTaxTotalPrice(totalTaxPrice); // 累加税总价
        invoiceCountVO.setReconciliationPrice(reconciliationPrice); // 累加总价
        return YResult.success(invoiceCountVO);
    }

    private void enrichReconciliationOrderVO(ReconciliationOrderVO vo, BamuReconciliation reconciliation) {
        // 假设 BamuReconciliation 中有 getReconciliationStartDate() 方法
        if (reconciliation != null) {
            vo.setReconciliationStartDate(reconciliation.getReconciliationStartDate());
            vo.setReconciliationEndDate(reconciliation.getReconciliationEndDate());
        }
    }


    private ReconciliationOrderVO daoToVo8(BamuReconciliationOrder bamuReconciliationOrder) {
        ReconciliationOrderVO reconciliationOrderVO = new ReconciliationOrderVO();
        BeanUtils.copyProperties(bamuReconciliationOrder, reconciliationOrderVO);
//        reconciliationOrderVO.setReconciliationStartDate(bamuReconciliationOrder.getReconciliationStartDate());
//        reconciliationOrderVO.setReconciliationEndDate(bamuReconciliationOrder.getReconciliationEndDate());
        return reconciliationOrderVO;
    }

    // 调整方法参数命名以更准确地反映其用途
    private List<ReconciliationOrderVO> daoToVoList1(List<BamuReconciliationOrder> bamuReconciliationOrderList, BamuReconciliation reconciliation) {
        return bamuReconciliationOrderList.stream().map(order -> daoToVo1(order, reconciliation))
                .collect(Collectors.toList());
    }

    private ReconciliationOrderVO daoToVo1(BamuReconciliationOrder bamuReconciliationOrder, BamuReconciliation reconciliation) {
        ReconciliationOrderVO reconciliationOrderVO = new ReconciliationOrderVO();
        BeanUtils.copyProperties(bamuReconciliationOrder, reconciliationOrderVO);
        reconciliationOrderVO.setReconciliationStartDate(reconciliation.getReconciliationStartDate());
        reconciliationOrderVO.setReconciliationEndDate(reconciliation.getReconciliationEndDate());
        return reconciliationOrderVO;
    }

    @Override
    public YResult<String> saveProject(ProjectDto saveDto) {
        LambdaQueryWrapper<BamuReconciliationSettlement> projectWrapper = new LambdaQueryWrapper<BamuReconciliationSettlement>()
                .in(BamuReconciliationSettlement::getId, saveDto.getIdList());
        List<BamuReconciliationSettlement> list = iBamuReconciliationSettlementService.list(projectWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                BamuInvoiceSource bamuInvoiceSource = new BamuInvoiceSource();
                BeanUtils.copyProperties(list.get(i), bamuInvoiceSource);
                bamuInvoiceSource.setInvoiceId(saveDto.getInvoiceId());
                bamuInvoiceSource.setBizId(list.get(i).getId());
                iBamuInvoiceSourceService.saveOrUpdate(bamuInvoiceSource);
            }
        }
        return YResult.success("关联成功");
    }

    @Override
    public YResult<PageResult<InvoiceSourceOrderVO>> getInvoiceSourceOrderById(InvoiceSourceOrderDto invoiceSourceOrderDto) {
        LambdaQueryWrapper<BamuInvoiceSourceOrder> wrapper = new LambdaQueryWrapper<BamuInvoiceSourceOrder>()
                .eq(BamuInvoiceSourceOrder::getInvoiceId, invoiceSourceOrderDto.getInvoiceId());
//        BamuInvoiceSourceOrder bamuInvoice = iBamuInvoiceSourceOrderService.getOne(wrapper);

        // 分页查询
        IPage<BamuInvoiceSourceOrder> invoicePage = new Page<>(invoiceSourceOrderDto.getPageIndex(), invoiceSourceOrderDto.getPageSize());
        invoicePage = iBamuInvoiceSourceOrderService.page(invoicePage, wrapper);
        // 处理查询结果
        if (CollectionUtils.isEmpty(invoicePage.getRecords())) {
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<InvoiceSourceOrderVO> invoiceVOList = daoToVoList4(invoicePage.getRecords());
        // 返回分页结果
        return YResult.success(new PageResult<>(invoiceVOList, invoicePage.getCurrent(), invoicePage.getSize(), invoicePage.getPages(), invoicePage.getTotal()));
    }

    @Override
    public YResult<PageResult<InvoiceSourceOrderVO>> getInvoiceSourceOrderBycontractId(InvoiceSourceOrderDto invoiceSourceOrderDto) {
        LambdaQueryWrapper<BamuInvoiceSourceOrder> wrapper = new LambdaQueryWrapper<BamuInvoiceSourceOrder>()
                .in(BamuInvoiceSourceOrder::getBizId, invoiceSourceOrderDto.getIdList());
//        BamuInvoiceSourceOrder bamuInvoice = iBamuInvoiceSourceOrderService.getOne(wrapper);

        // 分页查询
        IPage<BamuInvoiceSourceOrder> invoicePage = new Page<>(invoiceSourceOrderDto.getPageIndex(), invoiceSourceOrderDto.getPageSize());
        invoicePage = iBamuInvoiceSourceOrderService.page(invoicePage, wrapper);
        // 处理查询结果
        if (CollectionUtils.isEmpty(invoicePage.getRecords())) {
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<InvoiceSourceOrderVO> invoiceVOList = daoToVoList4(invoicePage.getRecords());
        // 返回分页结果
        return YResult.success(new PageResult<>(invoiceVOList, invoicePage.getCurrent(), invoicePage.getSize(), invoicePage.getPages(), invoicePage.getTotal()));
    }

    public YResult<PageResult<InvoiceSourceVO>> getInvoiceSourceById(InvoiceSourceDto invoiceSourceDto) {
        LambdaQueryWrapper<BamuInvoiceSource> wrapper = new LambdaQueryWrapper<BamuInvoiceSource>()
                .eq(BamuInvoiceSource::getInvoiceId, invoiceSourceDto.getInvoiceId());
//        BamuInvoiceSourceOrder bamuInvoice = iBamuInvoiceSourceOrderService.getOne(wrapper);

        // 分页查询
        IPage<BamuInvoiceSource> invoicePage = new Page<>(invoiceSourceDto.getPageIndex(), invoiceSourceDto.getPageSize());
        invoicePage = iBamuInvoiceSourceService.page(invoicePage, wrapper);
        // 处理查询结果
        if (CollectionUtils.isEmpty(invoicePage.getRecords())) {
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<InvoiceSourceVO> invoiceVOList = daoToVoList3(invoicePage.getRecords());
        // 返回分页结果
        return YResult.success(new PageResult<>(invoiceVOList, invoicePage.getCurrent(), invoicePage.getSize(), invoicePage.getPages(), invoicePage.getTotal()));
    }

    @Override
    public YResult<String> saveBindId(InvoiceDto saveDto) {
        LambdaQueryWrapper<BamuInvoice> wrapper = new LambdaQueryWrapper<BamuInvoice>()
                .in(BamuInvoice::getId, saveDto.getBindId());
        BamuInvoice bamuInvoice = iBamuInvoiceService.getOne(wrapper);
        if (bamuInvoice.getInvoiceBindStatus().equals("0")) {
            return YResult.error("该发票已关联其他发票");
        }
        bamuInvoice.setInvoiceBindId(saveDto.getBindtoId());
        bamuInvoice.setInvoiceBindStatus("1");
        iBamuInvoiceService.saveOrUpdate(bamuInvoice);
        return YResult.success("绑定成功");
    }

    @Override
    public YResult<String> redInvoice(InvoiceDto saveDto) {
        LambdaQueryWrapper<BamuInvoice> wrapper = new LambdaQueryWrapper<BamuInvoice>()
                .in(BamuInvoice::getId, saveDto.getId());
        BamuInvoice bamuInvoice = iBamuInvoiceService.getOne(wrapper);
        BamuInvoice bamuInvoice1 = new BamuInvoice();
        BeanUtils.copyProperties(bamuInvoice, bamuInvoice1);
        bamuInvoice.setInvoicingStatus(2);
        bamuInvoice.setSourceInvoiceId(bamuInvoice.getId());
        bamuInvoice.setRelatedAmount(bamuInvoice.getRelatedAmount());
        iBamuInvoiceService.saveOrUpdate(bamuInvoice1);
        return YResult.success("红冲成功");
    }

    @Override
    public YResult<String> saveStatus(InvoiceDto saveDto) {
        BamuInvoice bamuInvoice = iBamuInvoiceService.getById(saveDto.getId());
        bamuInvoice.setStatus(1);
        LocalDateTime localDateTime = LocalDateTime.now();
        // 使用系统默认时区将LocalDateTime转换为ZonedDateTime
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
        // 将ZonedDateTime转换为Date
        Date date = Date.from(zonedDateTime.toInstant());
        bamuInvoice.setApplyDate(date);
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        bamuInvoice.setApplyName(userInfo.getRealName());
        iBamuInvoiceService.saveOrUpdate(bamuInvoice);
        return YResult.success("提交成功");
    }

    @Override
    public YResult<String> ycconfirm(InvoiceConfirmDto invoiceConfirmDto) {
        // 提取DTO中的ID和其他确认信息
        String id = invoiceConfirmDto.getId();
        String invoiceConfirmPerson =
                invoiceConfirmDto.getInvoiceConfirmPerson();
        String invoiceConfirmMark =
                invoiceConfirmDto.getInvoiceConfirmMark();
        Boolean isConfirmInvoice = invoiceConfirmDto.getIsconfirm();
        // 根据ID获取结算信息，确保未被删除
        BamuInvoice invoice =
                iBamuInvoiceService.getByIdNoDelete(id);
        if (Objects.isNull(invoice)) {
            // 若找不到结算信息，返回错误结果
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 检查结算状态是否为供应商已确认
        Integer status = invoice.getStatus();
        if (status != Integer.valueOf(1)) {
            // 若状态不正确，返回错误结果
            return YResult.error(ResultMsgEnum.RECONCILIATION_SETTLEMENT_STAY_CONFIRMED);
        }
        // 更新结算状态为云采购已确认，并保存确认凭证和标记
        invoice.setStatus(Integer.valueOf(3));

        if (ConvertUtil.isValidEmptyJson(invoiceConfirmDto.getFile())) {
            invoice.setInvoicingFile("[]");
        } else {
            invoice.setInvoicingFile(invoiceConfirmDto.getFile());
        }
        iBamuInvoiceService.updateById(invoice);

        // 记录审核确认历史
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        iBamuAuditConfirmHistoryService.insertRecord2(invoice.getId(), invoice.getInvoicingFile(), 4, userInfo.getRealName(), invoiceConfirmMark);

        // 返回操作成功的结果
        return YResult.success(invoice.getId());
    }


    private List<InvoiceSourceOrderVO> daoToVoList4(List<BamuInvoiceSourceOrder> records) {
        return records.stream().map(this::daoToVo4).collect(Collectors.toList());
    }

    private InvoiceSourceOrderVO daoToVo4(BamuInvoiceSourceOrder bamuInvoice) {
        InvoiceSourceOrderVO invoiceVO = new InvoiceSourceOrderVO();
        BeanUtils.copyProperties(bamuInvoice, invoiceVO);
        return invoiceVO;
    }

    private List<InvoiceSourceVO> daoToVoList3(List<BamuInvoiceSource> records) {
        return records.stream().map(this::daoToVo3).collect(Collectors.toList());
    }

    private InvoiceSourceVO daoToVo3(BamuInvoiceSource bamuInvoice) {
        InvoiceSourceVO invoiceVO = new InvoiceSourceVO();
        BeanUtils.copyProperties(bamuInvoice, invoiceVO);
// 使用“至”作为分隔符拆分字符串
        String[] dates = invoiceVO.getReconciliationCycle().split("至");

        // 验证拆分结果是否包含两个日期
        if (dates.length == 2) {
            invoiceVO.setReconciliationStartDate(ConvertUtil.getString2Date(dates[0])); // 第一个日期
            invoiceVO.setReconciliationEndDate(ConvertUtil.getString2Date(dates[1])); // 第二个日期
        }
        invoiceVO.setYkorderInvoiceNum(getnum(bamuInvoice));
        return invoiceVO;
    }

    private Integer getnum(BamuInvoiceSource bamuInvoice) {
        LambdaQueryWrapper<BamuInvoiceApply> wrapper = new LambdaQueryWrapper<BamuInvoiceApply>()
                .eq(BamuInvoiceApply::getInvoiceId, bamuInvoice.getInvoiceId());
        List<BamuInvoiceApply> bamuInvoiceApplyList = iBamuInvoiceApplyService.list(wrapper);
        int num = 0;
        for (BamuInvoiceApply bamuInvoiceApply : bamuInvoiceApplyList) {
            LambdaQueryWrapper<BamuPurchaseApply> wrapper1 = new LambdaQueryWrapper<BamuPurchaseApply>()
                    .eq(BamuPurchaseApply::getId, bamuInvoiceApply.getApplyId());
            BamuPurchaseApply bamuPurchaseApply = iBamuPurchaseApplyService.getOne(wrapper1);

            if (bamuPurchaseApply.getProjectInvoiceStatus().equals("1")) {
                num = num + 1;
            }
        }
        return num;
    }

    @Override
    public List<InvoiceExcelDto> export(InvoiceDto invoiceDto) {
       //构建查询条件
        LambdaQueryWrapper<BamuInvoice> queryWrapper = new LambdaQueryWrapper<BamuInvoice>().
//                eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuReconciliation::getContractId,invoiceDto.getContractId()).
        like(StringUtils.isNotBlank(invoiceDto.getContractNo()), BamuInvoice::getContractNo, invoiceDto.getContractNo())
                .like(StringUtils.isNotBlank(invoiceDto.getContractName()), BamuInvoice::getContractName, invoiceDto.getContractName())
                .eq(StringUtils.isNotBlank(invoiceDto.getProjectId()), BamuInvoice::getProjectId, invoiceDto.getProjectId())
                .like(StringUtils.isNotBlank(invoiceDto.getProjectName()), BamuInvoice::getProjectName, invoiceDto.getProjectName())
                .eq(StringUtils.isNotBlank(invoiceDto.getPurchaseDeptId()), BamuInvoice::getPurchaseDeptId, invoiceDto.getPurchaseDeptId())
                .like(StringUtils.isNotBlank(invoiceDto.getPurchaseDeptName()), BamuInvoice::getPurchaseDeptName, invoiceDto.getPurchaseDeptName())
//                .eq(StringUtils.isNotBlank((CharSequence) invoiceDto.getInvoicingDate()),BamuInvoice::getInvoicingDate,invoiceDto.getInvoicingDate())
                .between(StringUtils.isNotBlank(invoiceDto.getBeginDate()) && StringUtils.isNotBlank(invoiceDto.getEndDate()), BamuInvoice::getInvoicingDate,
                        ConvertUtil.getStartOfDay(ConvertUtil.getString2Date(invoiceDto.getBeginDate())), ConvertUtil.getEndOfDay(ConvertUtil.getString2Date(invoiceDto.getEndDate())))
                .eq(StringUtils.isNotBlank((CharSequence) invoiceDto.getInvoicingPrice()), BamuInvoice::getInvoicingPrice, invoiceDto.getInvoicingPrice())
//                .eq(StringUtils.isNotBlank(invoiceDto.getInvoicingStatus()),BamuInvoice::getInvoicingStatus,invoiceDto.getInvoicingStatus())
                .eq(StringUtils.isNotBlank(invoiceDto.getInvoiceBindStatus()), BamuInvoice::getInvoiceBindStatus, invoiceDto.getInvoiceBindStatus())
                .in(!Objects.isNull(invoiceDto.getStatusList()), BamuInvoice::getStatus, invoiceDto.getStatusList())
//                .eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuInvoice::getStatus,invoiceDto.getStatusList())
                .eq(StringUtils.isNotBlank(invoiceDto.getContractMethod()), BamuInvoice::getContractMethod, invoiceDto.getContractMethod())
                .eq(BamuInvoice::getInvoiceDataType, 0)
                .eq(BamuInvoice::getIsDeleted, 0)
                .orderByDesc(BamuInvoice::getCreatedAt)
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuInvoice::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()), BamuInvoice::getSupplierDeptId, BaseContext.getSupplierList());
//                .eq(StringUtils.isNotBlank(invoiceDto.getInvoiceDataType()),BamuInvoice::getInvoiceDataType,invoiceDto.getInvoiceDataType());
//                .eq(StringUtils.isNotBlank(invoiceDto.getStatus()),BamuInvoice::getStatus,invoiceDto.getStatus());
        List<BamuInvoice> contractMaterialList  = iBamuInvoiceService.list(queryWrapper);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(contractMaterialList)){
            return contractMaterialList.stream().map(this::convertToExcelDto).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
    /**
     * 将BamuContractMaterial转化成ContractMaterialExportDto
     */
    private InvoiceExcelDto convertToExcelDto(BamuInvoice bamuPurchaseApply){
        InvoiceExcelDto dto = new InvoiceExcelDto();
        BeanUtils.copyProperties(bamuPurchaseApply,dto);
        dto.setId(bamuPurchaseApply.getId());
        return dto;
    }
}
